package com.jack006.exception;

import com.jack006.grace.result.GraceJSONResult;
import com.jack006.grace.result.ResponseStatusEnum;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Classname GraceExceptionHandler
 * @Description 统一异常的拦截器
 * 可以针对异常的类型进行捕获，然后返回 json 信心到前端
 * @Date 2021-06-13 15:44
 * @Created by jack
 */
@ControllerAdvice
public class GraceExceptionHandler {

    @ExceptionHandler(MyCustomerException.class)
    @ResponseBody
    public GraceJSONResult returnMyException(MyCustomerException e) {
        e.printStackTrace();
        return GraceJSONResult.exception(e.getResponseStatusEnum());
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseBody
    public GraceJSONResult returnMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
        return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_MAX_SIZE_ERROR);
    }

    /**
     * 校验 BO 对象的信息
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public GraceJSONResult returnMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errors = getErrors(bindingResult);
        return GraceJSONResult.errorMap(errors);
    }


    /**
     * 获取 BO 中的错误信息
     * @param result
     */
    public Map<String,String> getErrors(BindingResult result) {
        List<FieldError> fieldErrors = result.getFieldErrors();
        // 发送验证错误的时候所对应的某个属性  验证的错误信息
        Map<String,String> map = fieldErrors.stream().collect(Collectors.toMap(FieldError::getField,FieldError::getDefaultMessage));
        return map;
    }
}
